package com.longcai.service.impl.sys;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.longcai.bean.ApiResult;
import com.longcai.bean.PageHelper;
import com.longcai.entity.auth.SysShopsRoleUser;
import com.longcai.entity.auth.SysShopsUser;
import com.longcai.entity.auth.vo.SysShopsUserVo;
import com.longcai.entity.sys.SysUser;
import com.longcai.mapper.SysShopsRoleUserMapper;
import com.longcai.mapper.SysShopsUserMapper;
import com.longcai.page.table.PageTableResponse;
import com.longcai.service.sys.SysShopsUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ZJ
 * @since 2019-03-16
 */
@Service
public class SysShopsUserServiceImpl extends ServiceImpl<SysShopsUserMapper, SysShopsUser> implements SysShopsUserService {

    private static final Logger logger = LoggerFactory.getLogger(SysShopsUserServiceImpl.class);

    @Autowired
    private SysShopsUserMapper sysUserMapper;
    @Autowired
    private SysShopsRoleUserMapper sysRoleUserMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public SysShopsUser getUser(String username) {
        QueryWrapper<SysShopsUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return this.sysUserMapper.selectOne(queryWrapper);
    }

    @Override
    public PageTableResponse sysUserlistPage(SysShopsUser sysUser, PageHelper pageHelper) {

        Page<SysShopsUser> page = new Page<SysShopsUser>(pageHelper.getStart(), pageHelper.getLength());
        QueryWrapper<SysShopsUser> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(sysUser.getUsername())) {
            queryWrapper.eq("username", sysUser.getUsername());
        }
        if (!StringUtils.isEmpty(sysUser.getNickname())) {
            queryWrapper.eq("nickname", sysUser.getNickname());
        }
        if (!StringUtils.isEmpty(sysUser.getStatus())) {
            queryWrapper.eq("status", sysUser.getStatus());
        }

        IPage<SysShopsUser> sysUserIPage = this.sysUserMapper.selectPage(page, queryWrapper);
        PageTableResponse pageTableResponse = new PageTableResponse(sysUserIPage.getTotal(), sysUserIPage.getTotal(), sysUserIPage.getRecords());

        return pageTableResponse;
    }

    @Override
    public ApiResult<SysShopsUser> getSysUserById(String id) {
        SysShopsUser sysUser = this.sysUserMapper.selectById(id);
        return ApiResult.success(sysUser);
    }

    /**
     * 修改用户信息
     *
     * @param sysUserVo
     * @return
     */
    @Override
    @Transactional
    public SysShopsUser updateSysUser(SysShopsUserVo sysUserVo) {
        sysUserMapper.updateById(sysUserVo);
        saveSysUserRoles(sysUserVo.getId(), sysUserVo.getRoleId());
        return sysUserVo;
    }

    @Override
    public SysShopsUser saveSysUser(SysShopsUserVo sysUserVo) {
        SysShopsUser sysUser = sysUserVo;
        sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
        sysUser.setStatus(SysUser.Status.VALID);

        this.sysUserMapper.insert(sysUser);
        this.saveSysUserRoles(sysUser.getId(), sysUserVo.getRoleId());
        logger.debug("新增用户{}", sysUser.getUsername());

        return sysUser;
    }

    //修改密码
    @Override
    public ApiResult<SysShopsUser> updatePassword(SysShopsUser sysUser,String newPassword) {
        QueryWrapper<SysShopsUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", sysUser.getUsername());
        
//        queryWrapper.eq("password",passwordEncoder.encode(sysUser.getPassword()));
        SysShopsUser user = this.sysUserMapper.selectOne(queryWrapper);
        if (user == null) {
            return ApiResult.fail("密码错误");
        }
        //解密密码进行比较
        boolean matches = passwordEncoder.matches(sysUser.getPassword(), user.getPassword());
        if(!matches) {
            return ApiResult.fail("输入旧密码错误");
        }
        user.setPassword(passwordEncoder.encode(newPassword));
        sysUserMapper.updateById(user);
        ApiResult.success();
        return ApiResult.success();
    }

    /**
     * 添加角色中间表
     *
     * @param userId
     * @param roleId
     */
    private void saveSysUserRoles(String userId, String roleId) {
        if (roleId != null) {
            sysRoleUserMapper.deleteById(userId);
            if (roleId != null) {
                SysShopsRoleUser sysRoleUser = new SysShopsRoleUser(userId, roleId);
                sysRoleUserMapper.insert(sysRoleUser);
            }
        }
    }
}
